﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Web;
using System.IO.Compression;
using System.Text.RegularExpressions;
using System.Web.UI;


namespace Fly.Net
{
    public static class HttpUtils
    {
        /// <summary>
        /// 替换边框样式中 pt 为 px
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string BorderPtToPx(string html)
        {
            var reg = new Regex(@"border-.{2,20}:[\d.]+pt", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            return reg.Replace(html, o =>
            {
                return o.Value.TrimEnd('t', 'T') + "x";
            });
        }


        /// <summary>
        /// 写入页面的 DOCTYPE
        /// </summary>
        public static void WriteDocType()
        {
            if (HttpContext.Current.Request.Browser.Browser == "IE" && HttpContext.Current.Request.Browser.MajorVersion == 6)
            {

            }
            else
            {
                HttpContext.Current.Response.Write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
            }
        }

        /// <summary>
        /// 是否已用GZip压缩
        /// </summary>
        public static bool IsCompressedByGZip
        {
            get { return HttpContext.Current.Response.Filter is GZipStream; }
        }

        /// <summary>
        /// 是否已用Deflate压缩
        /// </summary>
        public static bool IsCompressedByDeflate
        {
            get { return HttpContext.Current.Response.Filter is DeflateStream; }
        }

        /// <summary>
        /// 是否已压缩
        /// </summary>
        public static bool IsCompressed
        {
            get { return IsCompressedByGZip || IsCompressedByDeflate; }
        }

        /// <summary>
        /// 开启 Gzip 或 Deflate 压缩
        /// </summary>
        public static void EnableCompress()
        {   
            if (IsCompressed)
                return;

            var encoding = HttpContext.Current.Request.ServerVariables["HTTP_ACCEPT_ENCODING"].ToLower();
            var canGzip = false;
            var canDeflate = false;

            if (!string.IsNullOrEmpty(encoding))
            {
                canGzip = encoding.Contains("gzip");
                canDeflate = encoding.Contains("deflate");
            }

            if (canDeflate)
            {
                HttpContext.Current.Response.Filter = new DeflateStream(HttpContext.Current.Response.Filter, CompressionMode.Compress);
                HttpContext.Current.Response.AppendHeader("Content-Encoding", "deflate");
            }
            else if (canGzip)
            {
                HttpContext.Current.Response.Filter = new GZipStream(HttpContext.Current.Response.Filter, CompressionMode.Compress);
                HttpContext.Current.Response.AppendHeader("Content-Encoding", "gzip");
            }           
        }

        /// <summary>
        /// 转换为绝对路径
        /// </summary>
        /// <param name="url">Url</param>
        /// <returns></returns>
        public static string ToAbsolute(string url)
        {
            try
            {
                return VirtualPathUtility.ToAbsolute(url);
            }
            catch
            {
                try
                {
                    var page = HttpContext.Current.Handler as Page;
                    if (page != null)
                        return page.ResolveUrl(url);
                }
                catch { }
            }

            if (url.StartsWith("/"))
                return url;

            if (url.StartsWith("~/"))
            {
                var root = HttpRuntime.AppDomainAppVirtualPath;
                return root.TrimEnd('/') + url.Substring(1);
            }

            if (url.StartsWith("."))
            {
                return Regex.Replace(HttpContext.Current.Request.Path, @"\/?[^/]+$", "") + "/" + url;
            }
            return url;
        }
    }
}
